package com.slf.engine.services.helper;


import java.util.List;

import org.apache.commons.httpclient.Cookie;
import org.apache.commons.httpclient.NameValuePair;
import org.apache.log4j.Logger;
import org.apache.log4j.Priority;
import com.slf.engine.bo.Order;
import com.slf.engine.bo.WaitBean;
import com.slf.engine.common.SysContext;
import com.slf.engine.utils.DateUtils;
import com.slf.engine.utils.MyUtils;
import com.zhkj.wsaction.type.TPacket;


public class ServiceHelper {

	private static final Logger log = Logger.getLogger(ServiceHelper.class);
	
	public static long contentLength(List<NameValuePair> params)
	{
		String s = "";
		for(int i = 0; i < params.size(); i++)
		{
			if(i == 0)
			{
				s += params.get(i).getName() + "=" + params.get(i).getValue();
			}else{
				s += "&" + params.get(i).getName() + "=" + params.get(i).getValue();
			}
		}
		
		return s.length();
	}
	
	public static String cookieStr(Cookie[] cookies)
	{
		String cookie = "";
		if(cookies != null && cookies.length > 0)
		{
			for(int i = 0; i < cookies.length;i++)
			{
				if(i == 0)
				{
					cookie += cookies[i].getName() + "=" + cookies[i].getValue();
				}else{
					cookie += "; " + cookies[i].getName() + "=" + cookies[i].getValue();
				}
				
			}
			return cookie;
		}
		return cookies.toString();
	}
	
	/**
	 * 放入查询队列
	 * @param order
	 * @return
	 */
	public static boolean putToCache(Order order)
	{
		log.log(Priority.INFO, "进入查询等待orderId:" + order.getOrderId() + " account:" + order.getAccount() + " money:" + order.getMoney() + " clbz:" + order.getClbz());
		WaitBean waitBean = new WaitBean();
		synchronized (SysContext.QUERY_MAP) {
			if(!SysContext.QUERY_MAP.containsKey(order.getOrderId()))
			{
				waitBean.setOrder(order);
				waitBean.setIsStart(true);
				waitBean.setTimeout(System.currentTimeMillis());
				SysContext.QUERY_MAP.put(order.getOrderId(), waitBean);
				waitBean.start();
				return true;
			}
		}
		return false;
	}
	
	/**
	 * 放入通知队列
	 */
	public static boolean putToNotice(Order order)
	{
		int i = order.getTzcs();
		order.setTzcs(i++);
		order.setNexttzsj(System.currentTimeMillis() + (long)Math.pow(order.getTzcs(),2));
		SysContext.NOTICE_LIST.add(order);
		return false;
	}
	
	public static Order putPacketToOrder(TPacket packet)
	{
		Order order = new Order();
		order.setOrderId(packet.readFromVarDataAsStr("CZID"));
		order.setAccount(packet.readFromVarDataAsStr("BCZSJH"));
		order.setMoney(String.valueOf(Integer.parseInt(packet.readFromVarDataAsStr("CZJE"))/100));
		order.setStarttime(DateUtils.strDate("yyyy-MM-dd HH:mm:ss"));
		return order;
	}
	
	public static String getBackMsg(String s)
	{
		s = s.replaceAll(";&#", ";");
		s = s.replaceAll("&#", ";");
		String ss[] = s.split("\\;");
		String s1 = "";
		for(int i = 0;i < ss.length;i++)
		{
			s1 += MyUtils.unicode2String(ss[i]);
		}
		return s1;
	}
}
